import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'app_color.dart';

class Utils {
  static const deFaultDurationTime = 500;

  static Size boundingTextSize(String? text, TextStyle style,
      {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (text == null || text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        text: TextSpan(text: text, style: style),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  static AppBar commonAppBar({String title = '', bool centerTitle = true}) {
    return AppBar(
      title: Text(
        title,
        style: TextStyle(fontSize: 18, color: AppColors.color202020),
      ),
      backgroundColor: AppColors.colorD7FFDF,
      flexibleSpace: FlexibleSpaceBar(
        background: Image.asset(
          //或者Image.network
          'assets/images/navi_bg.png',
          fit: BoxFit.fill,
        ),
      ),
      leading: InkWell(
        child: Image.asset(
          'assets/images/back_icon.png',
          width: 24,
          height: 24,
        ),
        onTap: () {
          Get.close(0);
        },
      ),
      elevation: 0,
      centerTitle: centerTitle,
    );
  }

  // 节流函数
  static const String deFaultThrottleId = 'DeFaultThrottleId';
  static Map<String, int> startTimeMap = {deFaultThrottleId: 0};
  static throttle(Function doSomething,
      {String throttleId = deFaultThrottleId,
      durationTime = deFaultDurationTime,
      required Function continueClick}) {
    int currentTime = DateTime.now().millisecondsSinceEpoch;
    if (currentTime - (startTimeMap[throttleId] ?? 0) > durationTime) {
      doSomething.call();
      startTimeMap[throttleId] = DateTime.now().millisecondsSinceEpoch;
    } else {
      continueClick.call();
    }
  }

  static Future<String> saveImageToFile(Uint8List imageData) async {
    Directory applicationDir = await getApplicationDocumentsDirectory();
    bool isDirExist = await Directory("${applicationDir.path}/images").exists();
    if (!isDirExist) await Directory("${applicationDir.path}/images").create();
    // 直接保存，返回的就是保存后的文件
    String fileName = "${DateTime.now().millisecondsSinceEpoch}.jpg";
    await File("${applicationDir.path}/images/$fileName")
        .writeAsBytes(imageData);
    return "/images/$fileName";
  }
}
